package com.plan.base.entity;

import com.plan.base.constant.BaseCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 返回结果
 *
 * @param <T>
 * @author zcl
 */
@Data
@Slf4j
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> implements Serializable {

    private static final long serialVersionUID = -3038921801127525265L;
    /**
     * 返回code码
     */
    private String code;
    /**
     * 返回信息
     */
    private String msg;
    /**
     * 上面信息模板参数
     */
    private Object[] args;
    /**
     * 分页信息
     */
    private Page page;
    /**
     * 返回数据实体
     */
    private T data;
    /**
     * 错误时要返给前端的数据
     */
    private Object errorData;
    /**
     * 国际化资源
     */
    private static final String BASE_NAME = "i18n/messages";

    /**
     * 非国际化的返回成功
     */
    public static <T> Result<T> ok() {
        return new Result<T>().setCode(BaseCode.OK);
    }

    public static <T> Result<T> ok(T data) {
        return new Result<T>().setCode(BaseCode.OK).setData(data);
    }

    public static <T> Result<T> fail(String code, Object... args) {
        return new Result<T>().setCode(code).setArgs(args);
    }

    public Result<T> setData(T data) {
        this.data = data;
        return this;
    }

    public Result<T> setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public Result<T> setArgs(Object... args) {
        this.args = args;
        return this;
    }

    public Result<T> setCode(String code) {
        this.code = code;
        return this;
    }


    public Result<T> setPage(Page page) {
        this.page = page;
        return this;
    }


    public Object getErrorData() {
        return errorData;
    }

    public Result<T> setErrorData(Object errorData) {
        this.errorData = errorData;
        return this;
    }

    public boolean isOk() {
        return this.code.equals(BaseCode.OK);
    }

    public static String getMessages(String code, Locale locale, Object... args) {
        if (locale == null) {
            // 默认汉语
            locale = Locale.SIMPLIFIED_CHINESE;
        }
        try {
            ResourceBundle messages = ResourceBundle.getBundle(BASE_NAME, locale);
            String msg = messages.getString(code);
            if (args == null || args.length == 0) {
                return msg;
            }
            // 使用 MessageFormat 类来格式化字符串，并传入参数
            return String.format(msg, args);
        } catch (Exception e) {
            log.warn("i18n getMessages exception", e);
            return null;
        }

    }
}
